package lightswitch.server.code.sqlhelper.expression;

import java.util.List;

import lightswitch.server.code.object.DataRow;
import lightswitch.server.code.object.MyEntry;
import lightswitch.server.code.sqlhelper.statement.select.From;
import lightswitch.server.code.sqlhelper.statement.select.Select;
import lightswitch.server.code.util.TypeOfData;

public class SingleExpression extends Expression {
	public String varName;

	public SingleExpression(String str) {
		varName = str;
	}

	public String toString() {
		return varName;
	}

	public Object GetValue(DataRow row, List<From> parentFromList) {
		if (varName.contains("select")) {
			Select _select = new Select(varName.substring(1,
					varName.length() - 1), parentFromList);
			NormalTable tb = _select.execute().getAsNormalTable();
			dataType = TypeOfData.TABLE;
			return tb;
		}

		if (varName.matches("[0-9-]+")) {
			dataType = TypeOfData.INT;
			return varName;
		} else {
			if (varName.matches("[0-9-.]+")) {
				dataType = TypeOfData.FLOAT;
				return varName;
			}

			String[] str = varName.split("\\.");
			if (str.length == 2) {
				String tb = str[0];
				String col = str[1];

				MyEntry _entry = row.getValue(tb, col);

				if (_entry == null) {
					// throw exception
					return null;
				}

				dataType = _entry.getDataType();

				return _entry.getValue();

			} else {
				if (str.length == 1) {
					if (varName.equals("true")) {
						dataType = TypeOfData.BOOLEAN;
						return true;
					} else {
						if (varName.equals("false")) {
							dataType = TypeOfData.BOOLEAN;
							return false;
						} else 
							if(varName.equals("null"))
							{
								dataType = TypeOfData.CHAR;
								return "null";
							}
							else
							{

							if (varName.matches("'.+'")) {
								dataType = TypeOfData.CHAR;
								return varName.substring(1,
										varName.length() - 1);
							} else {

								// thow Exception;
								return null;
							}
						}
					}
				}
			}
		}
		// throw exception
		return null;
	}

}
